package com.thread.signal.first;

/**
 * @description:
 * @author: 刘建楼
 * @create: 2021-04-20
 **/
public class Account3 {
    // 封装账户编号和账户余额的两个成员变量
    private String accountNo;
    private double balance;
    // 标识账户中是否已有存款的旗标
    private boolean flag = false;

    // 取钱者的操作
    public synchronized void draw(double drawAmount) {
        try {
            if (!flag) {
                wait();
            } else {
                // 执行取钱操作
                System.out.println(Thread.currentThread().getName() + "取钱：" + drawAmount);
                // 修改余额
                balance -= drawAmount;
                System.out.println("余额为:" + balance);
                flag = false;
                notifyAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 存款者操作
    public synchronized void deposit(double drawAmount) {
        try {
            if (flag) {
                wait();
            } else {
                // 执行存钱操作
                System.out.println(Thread.currentThread().getName() + "存钱：" + drawAmount);
                // 修改余额
                balance += drawAmount;
                System.out.println("余额为:" + balance);
                flag = true;
                notifyAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 下面两个方法根据accountNo来重写hashCOde()和equals()方法
    public int hashCode() {
        return accountNo.hashCode();
    }

    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        ;
        if (obj != null && obj.getClass() == Account3.class) {
            Account3 account2 = (Account3) obj;
            return account2.getAccountNo().equals(accountNo);
        }
        return false;
    }


    public Account3() {
    }

    public Account3(String accountNo, double balance) {
        this.accountNo = accountNo;
        this.balance = balance;
    }

    public String getAccountNo() {
        return accountNo;
    }

    public void setAccountNo(String accountNo) {
        this.accountNo = accountNo;
    }

    // 只提供get方法
    public double getBalance() {
        return balance;
    }

}
